package com.lipi.mall.cart.interceptor;

import com.lipi.common.constant.AuthServerConstant;
import com.lipi.common.constant.SystemConstant;
import com.lipi.common.vo.MemberRespVO;
import com.lipi.mall.cart.constant.CartConstant;
import com.lipi.mall.cart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 执行目标方法之前，判断用户的登录状态。并封装传递给controller
 */
//用户的登录状态分为
// 1、游客，未颁发user-key 2、游客，已颁发user-key  3、已登录

public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal();

    /**
     * 业务执行之前,执行该方法
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        UserInfoTo userInfoTo = new UserInfoTo();

        MemberRespVO member = (MemberRespVO) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (member != null) {
            //用户已登录
            userInfoTo.setUserId(member.getId());
        }

        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length == 0) {

            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
            //给post方法标识,方法执行完后让浏览器接受cookie
            userInfoTo.setTempUser(true);

        } else {

            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(CartConstant.LOGIN_USER)) {
                    //存在临时令牌
                    userInfoTo.setUserKey(cookie.getValue());
                }
            }

            // 不存在临时令牌,颁发临时令牌
            if (StringUtils.isEmpty(userInfoTo.getUserKey())) {
                String uuid = UUID.randomUUID().toString();
                userInfoTo.setUserKey(uuid);
                //给post方法标识,方法执行完后让浏览器接受cookie
                userInfoTo.setTempUser(true);
            }

        }

        threadLocal.set(userInfoTo);
        return true;
    }


    /**
     * 业务执行之后,执行该方法
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();

        //若浏览器不存在临时令牌,将生成的临时令牌发送给浏览器
        if (userInfoTo.isTempUser()) {
            Cookie cookie = new Cookie(CartConstant.LOGIN_USER, userInfoTo.getUserKey());
            cookie.setDomain(SystemConstant.SYSTEM_DOMAIN);
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);

            response.addCookie(cookie);
        }

    }
}
